package com.wyl.interceptor;

import java.lang.reflect.Method;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.wyl.annotation.Token;
import com.wyl.support.web.Message;

public class TokenInterceptor extends HandlerInterceptorAdapter {
	private ThreadLocal<Boolean> isRepeatSubmit= new ThreadLocal<Boolean>();
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.save();
                if (needSaveSession) {                	
                    request.getSession().setAttribute("token", UUID.randomUUID().toString());
                    isRepeatSubmit.set(false);
                }
                boolean needRemoveSession = annotation.remove();
                if (needRemoveSession) {
                   /* if (isRepeatSubmit(request)) {                    	
                        return false;
                    }*/
                	isRepeatSubmit.set(isRepeatSubmit(request));
                    request.getSession().removeAttribute("token");
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }
	
	@Override  
    public void postHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler,  
            ModelAndView modelAndView) throws Exception {
		if(isRepeatSubmit.get()!=null && isRepeatSubmit.get()){
			modelAndView.setViewName("/info/general");
			modelAndView.getModelMap().addAttribute("message", new Message("repeat.submit", Message.Type.DANGER));
			isRepeatSubmit.set(false);
		}
		super.postHandle(request, response, handler, modelAndView);          
    }  
	
	
    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession().getAttribute("token");
        String clinetToken = request.getParameter("token");
        if (serverToken == null || clinetToken == null || !serverToken.equals(clinetToken)) {
            return true;
        }       
        return false;
    }
}
